package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.constant.JobNatureEnum;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.platform.service.ISysUserRoleService;
import com.yuyou.fn.report.entity.ClassLectureDetail;
import com.yuyou.fn.report.service.IClassLectureDetailService;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wens on 2017/4/16.
 */
@Controller
@RequestMapping("/api/admin/attendance")
public class AdminAttendanceController  extends ApiBaseController {


    @Resource
    private IClassLectureService classLectureService ;

    @Resource
    private IAttendClassRecordDetailService attendClassRecordDetailService;

    @Resource
    private IAttendClassLectureService  attendClassLectureService;

    @Resource
    private IShiftClassRecordDetailService shiftClassRecordDetailService;

    @Resource
    private IShiftClassRecordService shiftClassRecordService;

    @Resource
    private IAttendClassRecordService attendClassRecordService;

    @Resource
    private IChangeClassService changeClassService;


    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private ICourseTemplateService courseTemplateService;

    @Resource
    private IClassLectureDetailService classLectureDetailService;

    @ApiOperation("根据期数日期得出上课时间")
    @RequestMapping(value = "/classTimeByPeriodDate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<String>> classTimeByPeriodDate(@ApiParam(value = "期数Id",required = true)@RequestParam("periodId")long periodId, @ApiParam("上课开始时间")@RequestParam("startClassDate")Date startClassDate,  @ApiParam("上课结束时间")@RequestParam("endClassDate")Date endClassDate, HttpServletRequest request) {

        DataPermission dataPermission = getDataPermission(request);
        List<String> classTimes=attendClassLectureService.findClassTimeByPeriodDate(dataPermission,periodId,startClassDate,endClassDate);
        return ReturnResult.success(classTimes);
    }

    @ApiOperation("考勤班级列表")
    @RequestMapping(value = "/attendClassLectureList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<AttendClassLecture>> attendClassLectureList(AttendClassLectureQueryVo attendClassLectureQueryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {

        DataPermission dataPermission = getDataPermission(request);

        Page<AttendClassLecture> page = attendClassLectureService.findAttendClassLectureByQuery(attendClassLectureQueryVo , dataPermission , pageNo , pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("导出考勤班级列表")
    @RequestMapping(value = "/exportAttendClassLecture", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportAttendClassLecture(AttendClassLectureQueryVo attendClassLectureQueryVo , HttpServletRequest request, HttpServletResponse response) throws IOException  {

        DataPermission dataPermission = getDataPermission(request);
        Page<AttendClassLecture> page = attendClassLectureService.findAttendClassLectureByQuery(attendClassLectureQueryVo , dataPermission , 1 , 50000 );
        List<AttendClassLecture> attendClassLectureList=page.getRecords();
        List<Long> classLectureIds = BeanUtils.toList(attendClassLectureList, "classLectureId");
        List<ClassLectureDetail> classLectureDetailList=classLectureDetailService.findByIds(classLectureIds,"classLectureId","jobNature");
        Map<Long, ClassLectureDetail> classLectureDetailMap = BeanUtils.toMap(classLectureDetailList, "classLectureId");

        Webs.writeExcel(request,response,attendClassLecture2excel(attendClassLectureList,classLectureDetailMap,sysUserRoleService.showIdNoByCheckRoleNames(Principals.get().id)),"考勤班级列表");
        return ReturnResult.success("ok");
    }

    SXSSFWorkbook attendClassLecture2excel(List<AttendClassLecture> attendClassLectureList,Map<Long, ClassLectureDetail> classLectureDetailMap,Boolean showIdNo) {
        List<Long> classIds = Utils.removeDuplicate(BeanUtils.toList(attendClassLectureList, "classId"));
        List<CourseClass> courseClassList=courseClassService.findByIds(classIds,"classId","courseTemplateId");
        Map<Long, CourseClass> classMap = BeanUtils.toMap(courseClassList, "classId");
        List<Long> courseTemplateIds = BeanUtils.toList(courseClassList, "courseTemplateId");
        List<CourseTemplate> courseTemplateList=courseTemplateService.findByIds(courseTemplateIds,"courseTemplateId","courseName");
        Map<Long, CourseTemplate> courseTemplateMap = BeanUtils.toMap(courseTemplateList, "courseTemplateId");
        List<Long> teacherIds=Utils.removeDuplicate(BeanUtils.toList(attendClassLectureList, "teacherId"));
        List<Teacher> teacherList=teacherService.findByIds(teacherIds);
        Map<Long,Teacher> teacherMap=BeanUtils.toMap(teacherList,"teacherId");
        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("考勤管理列表");
        SXSSFRow firstRow = sheet.createRow(0);
        String[] titles = new String[] {"班级编号","班级名称","课程名称","课程编号","段次","年级","科目","期名","校区","教室","讲次	","上课日期","上课时间","是否考勤","考勤时间","总人数","出勤人数","缺勤人数","迟到人数","请假人数","班主任","任课老师","任教性质","身份证"};


        CellStyle cellStyle = excel.createCellStyle();
        DataFormat dataFormat = excel.createDataFormat();
        cellStyle.setDataFormat(dataFormat.getFormat("#,##0.00"));

        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum=1;
        if (attendClassLectureList!=null){
            for (AttendClassLecture attendClassLecture:attendClassLectureList){
                ClassLectureDetail classLectureDetail=classLectureDetailMap.get(attendClassLecture.getClassLectureId());
                Teacher teacher=teacherMap.get(attendClassLecture.getTeacherId())==null?new Teacher():teacherMap.get(attendClassLecture.getTeacherId());

                SXSSFRow row = sheet.createRow(rowNum++);
                int cellNum=0;
                SXSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getClassNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getClassName()));

                CourseClass courseClass=classMap.get(attendClassLecture.getClassId());
                CourseTemplate courseTemplate=courseTemplateMap.get(courseClass.getCourseTemplateId());


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(courseTemplate==null?"":courseTemplate.getCourseName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(courseTemplate==null?"":courseTemplate.getCourseTemplateId().toString()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getSegmentNo()==null?"":attendClassLecture.getSegmentNo().toString());

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getSubjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getPeriodName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getRoomName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getLectureNo()==null?"":attendClassLecture.getLectureNo().toString());

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getClassDate()==null?"":Utils.formatDate(attendClassLecture.getClassDate(),"yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(attendClassLecture.getStartTime())+"-"+StringUtils.defaultString(attendClassLecture.getEndTime()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getAttendanceStatus()==1?"是":"否");

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getAttendanceTime()==null?"": Utils.formatDate(attendClassLecture.getAttendanceTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(attendClassLecture.getTotalAmount());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(attendClassLecture.getAttendanceAmount());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(attendClassLecture.getAbsenceAmount());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(attendClassLecture.getLateAmount());

                cell = row.createCell(cellNum++);
                cell.setCellType(CellType.NUMERIC);
                cell.setCellValue(attendClassLecture.getLeaveAmount());

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getSeniorName());

                cell = row.createCell(cellNum++);
                cell.setCellValue(attendClassLecture.getTeacherName());

                cell = row.createCell(cellNum++);
                cell.setCellValue(EnumUtils.getName(JobNatureEnum.values() ,classLectureDetail.getJobNature()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(showIdNo?teacher.getIdNo():"");
            }
        }


        return excel;
    }


    @ApiOperation("考勤列表")
    @RequestMapping(value = "/attendanceRecordList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<ClassLecture> > attendanceRecordList(@RequestParam("classId") Long classId, HttpServletRequest request) {
        List<ClassLecture> recordList = classLectureService.findClassLectureByClassId(classId);
        return ReturnResult.success(recordList);
    }

    @ApiOperation("考勤详情")
    @RequestMapping(value = "/attendanceRecordDetailList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<AttendClassRecordVo> > attendanceRecordDetailList(@RequestParam("classLectureId") Long classLectureId, HttpServletRequest request) {
        List<AttendClassRecordVo> recordDetailList = classLectureService.findAttendClassRecordDetailByClassLectureId(classLectureId);
        return ReturnResult.success(recordDetailList);
    }

    @ApiOperation("导出考勤详情")
    @RequestMapping(value = "/exportAttendanceRecordDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<AttendClassRecordVo> > exportAttendanceRecordDetail(@RequestParam("classLectureId") Long classLectureId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<AttendClassRecordVo> recordDetailList = classLectureService.findAttendClassRecordDetailByClassLectureId(classLectureId);
        SXSSFWorkbook excel=attendClassRecordDetailService.exportAttendanceRecordDetail(recordDetailList);
        Webs.writeExcel(request,response,excel ,"学生考勤详情");
        return ReturnResult.success(recordDetailList);
    }

    @ApiOperation("保存考勤详情")
    @RequestMapping(value = "/saveAttendanceRecordDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveAttendanceRecordDetail(@RequestParam("classLectureId") Long classLectureId , @RequestParam("details") String detailsStr, HttpServletRequest request) {

        List<AttendClassRecordUpdateVo> details = JSONObject.parseObject(detailsStr, new TypeReference<List<AttendClassRecordUpdateVo>>() {
        });
        classLectureService.updateAttendClassRecord(classLectureId , details,ClassLecture.AttendanceRoleEnum.人工.ordinal());
        return ReturnResult.success("OK");
    }
    @ApiOperation("保存预考勤详情")
    @RequestMapping(value = "/saveAttendanceRecordAdvanceDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveAttendanceRecordAdvanceDetail( @RequestParam("details") String detailsStr, HttpServletRequest request) {

        List<AttendClassRecordUpdateVo> details = JSONObject.parseObject(detailsStr, new TypeReference<List<AttendClassRecordUpdateVo>>() {
        });
        classLectureService.updateAttendClassAdvanceStatus(details);
        return ReturnResult.success("OK");
    }


    @ApiOperation("设置考勤备注")
    @RequestMapping(value = "/setUpAttendanceRemark", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> setUpAttendanceRemark(@RequestParam("attendClassRecordId") Long attendClassRecordId , @RequestParam("remark") String remark, HttpServletRequest request) {

        attendClassRecordService.setUpAttendClassRemark(attendClassRecordId , remark);
        return ReturnResult.success("OK");
    }


    @ApiOperation("学生考情纪录详情列表")
    @RequestMapping(value = "/attendClassRecordDetailList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<AttendClassRecordDetail>>  attendClassRecordDetailList (AttendClassRecordDetailQueryVo attendClassRecordDetailQueryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize, HttpServletRequest request) {
        DataPermission dataPermission = getDataPermission(request);
        Page<AttendClassRecordDetail> page = attendClassRecordDetailService.findAttendClassRecordDetailForPage(attendClassRecordDetailQueryVo, dataPermission , pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出学生考情纪录详情")
    @RequestMapping(value = "/exportAttendClassRecordDetail", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<AttendClassRecordDetail>>  exportAttendClassRecordDetail (AttendClassRecordDetailQueryVo attendClassRecordDetailQueryVo , HttpServletRequest request , HttpServletResponse response ) throws IOException {
        DataPermission dataPermission = getDataPermission(request);
        Page<AttendClassRecordDetail> page = attendClassRecordDetailService.findAttendClassRecordDetailForPage(attendClassRecordDetailQueryVo, dataPermission , 1, 65535 );

        SXSSFWorkbook excel = new SXSSFWorkbook();
        SXSSFSheet sheet = excel.createSheet("报名纪录");

        String[] titles = new String[] { "区域","业务组","校区","教室","期数","班级编号","班级名称","段次","年级","科目","学生姓名","讲次","考勤情况","上课日期","上课时间","学号","手机号码","备注" };

        Map<Integer,String> attendanceStatusMap = new HashMap<>();
        attendanceStatusMap.put(0,"出勤");
        attendanceStatusMap.put(1,"缺勤");
        attendanceStatusMap.put(2,"迟到");
        attendanceStatusMap.put(3,"请假");

        int rowIndex  =  0 ;
        int columnIndex = 0 ;

        SXSSFRow row = sheet.createRow(rowIndex ++ );
        for(String head : titles){
            SXSSFCell cell = row.createCell(columnIndex++);
            cell.setCellValue(head);
        }

        List<AttendClassRecordDetail> attendClassRecordDetailList = page.getRecords();

        for(AttendClassRecordDetail attendClassRecordDetail : attendClassRecordDetailList){
            columnIndex = 0 ;
            row = sheet.createRow(rowIndex ++ );

            SXSSFCell cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getAreaTeamName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getBusTeamName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getCampusName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(attendClassRecordDetail.getRoomName()));


            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getPeriodName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getClassNo());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getClassName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getSegmentNo()==null?"":attendClassRecordDetail.getSegmentNo().toString());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(attendClassRecordDetail.getGradeName()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(attendClassRecordDetail.getSubjectName()));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getStudentName());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getLectureNo() == null ? StringUtils.EMPTY : String.valueOf(attendClassRecordDetail.getLectureNo() ));

            cell = row.createCell(columnIndex++);
            if(attendClassRecordDetail.getIsAttendance() != null && attendClassRecordDetail.getIsAttendance() == 1 ){
                cell.setCellValue(attendanceStatusMap.get(attendClassRecordDetail.getAttendanceStatus()));
            }else{
                cell.setCellValue(StringUtils.EMPTY);
            }

            cell = row.createCell(columnIndex++);
            cell.setCellValue(TimeUtils.date2String( attendClassRecordDetail.getClassDate() , " yyyy-MM-dd"));

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(attendClassRecordDetail.getStartTime()) + "-" + StringUtils.defaultString(attendClassRecordDetail.getEndTime()) );

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getStudentNo());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(attendClassRecordDetail.getStudentPhoneNo());

            cell = row.createCell(columnIndex++);
            cell.setCellValue(StringUtils.defaultString(attendClassRecordDetail.getRemark()));
        }

        Webs.writeExcel(request,response,excel ,"学生考勤");

        return ReturnResult.success(page);
    }


    @ApiOperation("调班记录")
    @RequestMapping(value = "/shiftRecordDetailList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ShiftClassRecordDetail>> shiftRecordDetailList(ShiftClassRecordDetailQueryVo query,@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo , @RequestParam(value = "pageSize",defaultValue = "20") Integer pageSize ) {
        Page<ShiftClassRecordDetail> page = shiftClassRecordDetailService.findShiftClassRecordDetailByQuery(query, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出调班记录")
    @RequestMapping(value = "/exportShiftClassRecordDetail",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportShiftClassRecordDetailByQuery(ShiftClassRecordDetailQueryVo shiftClassRecordDetailQueryVo, HttpServletRequest request,HttpServletResponse response) throws Exception{
        Webs.writeExcel(request,response, shiftClassRecordDetailService.exportShiftClassRecordDetailByQuery(shiftClassRecordDetailQueryVo), "调班记录");
        return ReturnResult.success("ok");
    }


    @ApiOperation("撤销调课")
    @RequestMapping(value = "/cancelShiftClass", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> cancelShiftClass(@RequestParam("shiftClassRecordId") Long shiftClassRecordId) {
        shiftClassRecordService.cancelShiftClass(shiftClassRecordId);
        return ReturnResult.success("OK");
    }



    @ApiOperation("转班记录")
    @RequestMapping(value = "/changeClassList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<ChangeClassDetailVo>> changeClassList(@ModelAttribute ChangeClassQueryVo  changeClassQueryVo, @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo , @RequestParam(value = "pageSize",defaultValue = "20") Integer pageSize ) {
        if (changeClassQueryVo.getEndDate()!=null){
            changeClassQueryVo.setEndDate(TimeUtils.changeOneDateLastTime(changeClassQueryVo.getEndDate()));
        }
        Page<ChangeClassDetailVo> page = changeClassService.findChangeClassDetailPage(changeClassQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }


    @ApiOperation("考勤预警")
    @RequestMapping(value = "/findAttendWarningPage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<AttendWarningVo> > findAttendWarningPage(@ModelAttribute AttendWarningQueryVo attendWarningQueryVo, @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo , @RequestParam(value = "pageSize",defaultValue = "20") Integer pageSize ) {
        Date date=TimeUtils.now();

        String nowTime=Utils.formatDate(date,"yyyy-MM-dd HH:mm");
        Page<AttendWarningVo> page = attendClassLectureService.findAttendWarningPage(attendWarningQueryVo, nowTime, pageNo, pageSize);
        return ReturnResult.success(page);
    }


    @ApiOperation("导出考勤预警")
    @RequestMapping(value = "/exportAttendWarning",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportAttendWarning(@ModelAttribute AttendWarningQueryVo attendWarningQueryVo, HttpServletRequest request,HttpServletResponse response) throws Exception{
        Date date=TimeUtils.now();
        String nowTime=Utils.formatDate(date,"yyyy-MM-dd HH:mm");
        Webs.writeExcel(request,response, attendClassLectureService.exportAttendWarningByQuery(attendWarningQueryVo,nowTime), "考勤预警");
        return ReturnResult.success("ok");
    }
}
